from fastapi import APIRouter, Depends, HTTPException, status

from app.dependencies_json import get_auth_service, get_current_user
from app.models.schemas import APIResponse, UserCreate, UserLogin, Token, UserInfo
from app.services.json_auth_service import JSONAuthService

router = APIRouter(tags=["authentication"])

@router.post("/register", response_model=APIResponse[UserInfo])
def register(
    user_data: UserCreate,
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """用户注册"""
    try:
        user_info = auth_service.create_user(user_data)
        return APIResponse(
            message="用户注册成功",
            data=user_info
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="注册失败"
        )

@router.post("/login", response_model=APIResponse[Token])
def login(
    login_data: UserLogin,
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """用户登录"""
    try:
        token = auth_service.login(login_data)
        if not token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
        
        return APIResponse(
            message="登录成功",
            data=token
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录失败"
        )

@router.post("/refresh", response_model=APIResponse[Token])
def refresh_token(
    refresh_token: str,
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """刷新访问令牌"""
    try:
        token = auth_service.refresh_token(refresh_token)
        if not token:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="刷新令牌无效"
            )
        
        return APIResponse(
            message="令牌刷新成功",
            data=token
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="令牌刷新失败"
        )

@router.get("/me", response_model=APIResponse[UserInfo])
def get_current_user_info(
    current_user: dict = Depends(get_current_user),
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """获取当前用户信息"""
    try:
        user_info = auth_service._dict_to_user_info(current_user)
        return APIResponse(
            message="获取用户信息成功",
            data=user_info
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户信息失败"
        )

@router.post("/logout", response_model=APIResponse[bool])
def logout(
    current_user: dict = Depends(get_current_user),
    auth_service: JSONAuthService = Depends(get_auth_service)
):
    """用户登出"""
    try:
        success = auth_service.logout(current_user['id'])
        return APIResponse(
            message="登出成功",
            data=success
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登出失败"
        )
